package com.ncucoder.soms.service.impl;

import com.ncucoder.soms.dao.RoleMapper;
import com.ncucoder.soms.dao.UserMapper;
import com.ncucoder.soms.dto.CreateUserDTO;
import com.ncucoder.soms.dto.DisplayUserDTO;
import com.ncucoder.soms.dto.UpdateUserDTO;
import com.ncucoder.soms.entity.Role;
import com.ncucoder.soms.entity.User;
import com.ncucoder.soms.service.UserService;
import com.ncucoder.soms.util.PasswordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date Jul 4, 2019
 */
@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public int updateLastLoginByUsername(String username, Date loginTime) {
        if (username == null || "".equals(username) || loginTime == null) {
            return 0;
        }
        return userMapper.updateLastLoginByUsername(username, loginTime);
    }

    @Override
    public int updatePasswordByUsername(String newPassword, String username) {

        if (newPassword == null || "".equals(newPassword)) {
            return 0;
        }

        String newSalt = PasswordUtils.generateSalt();
        newPassword = PasswordUtils.encrypt(newPassword, newSalt);
        return userMapper.updatePasswordByUsername(newPassword, newSalt, username);
    }

    @Override
    public List<DisplayUserDTO> listUsers(int page, int pageSize) {
        int beginIndex = pageSize * (page - 1);

        List<User> users = userMapper.selectUsers(beginIndex, pageSize);

        // 从User到DisplayUserDTO的转化: 增加角色字段
        List<DisplayUserDTO> displayUsers = new ArrayList<>();
        for (User user: users) {
            DisplayUserDTO displayUser = new DisplayUserDTO();
            displayUser.setPassword(user.getPassword());
            displayUser.setId(user.getId());
            displayUser.setUsername(user.getUsername());
            displayUser.setEmail(user.getEmail());
            displayUser.setPhone(user.getPhone());
            displayUser.setGender(user.getGender() == 0 ? "女" : "男");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date lastLogin = user.getLastLogin();
            displayUser.setLastLogin(lastLogin == null ? "" : simpleDateFormat.format(lastLogin));

            // 获取用户角色
            String role = userMapper.selectRoleByUsername(user.getUsername());
            role = "admin".equals(role) ? "管理员" : "普通用户";
            displayUser.setRole(role);
            displayUser.setAvatar(user.getAvatar());
            displayUsers.add(displayUser);
        }

        return displayUsers;
    }

    @Override
    public int deleteUserById(Long id) {
        return userMapper.deleteUserById(id);
    }

    @Override
    public int createUser(CreateUserDTO createUserDTO) {
        if (createUserDTO == null
                || createUserDTO.getUsername() == null || "".equals(createUserDTO.getUsername())
                || createUserDTO.getEmail() == null || "".equals(createUserDTO.getEmail())
                || createUserDTO.getRole() == null
                || createUserDTO.getPassword() == null || "".equals(createUserDTO.getPassword())
                || createUserDTO.getPhone() == null || "".equals(createUserDTO.getPhone())
                || createUserDTO.getGender() == null) {
            return 0;
        }

        User user = new User();
        user.setUsername(createUserDTO.getUsername());
        user.setEmail(createUserDTO.getEmail());
        String salt = PasswordUtils.generateSalt();

        user.setPassword(PasswordUtils.encrypt(createUserDTO.getPassword(), salt));
        user.setSalt(salt);
        user.setGender(createUserDTO.getGender());
        user.setPhone(createUserDTO.getPhone());

        userMapper.insertUser(user);

        User createdUser = userMapper.selectUserByUsername(user.getUsername());

        return userMapper.setRole(createdUser.getId(), createUserDTO.getRole());
    }

    @Override
    public int countUsers() {
        return userMapper.countUsers();
    }

    @Override
    public User getUserByUsername(String username) {
        if ("".equals(username) || username == null) {
            return null;
        }
        return userMapper.selectUserByUsername(username);
    }

    @Override
    public String getRoleByUsername(String username) {
        if ("".equals(username) || username == null) {
            return null;
        }
        return userMapper.selectRoleByUsername(username);
    }

    @Override
    public int updateUser(UpdateUserDTO updateUser) {

        if (userMapper.updateRole(updateUser.getId(), updateUser.getRole()) != 1) {
            return 0;
        }
        String salt = PasswordUtils.generateSalt();
        updateUser.setPassword(PasswordUtils.encrypt(updateUser.getPassword(), salt));
        updateUser.setSalt(salt);
        return userMapper.updateUserById(updateUser);
    }

}
